//
//  CreateGroupFinishViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/5.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "CreateGroupFinishViewController.h"
#import "FriendName.h"
#import "SelectFriendModel.h"
#import "AddGroupMemberTableViewCell.h"

@interface CreateGroupFinishViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *linkPeopleTableView;
@property (nonatomic, strong) NSMutableDictionary *friendNameDic; // 好友姓名字典
@property (nonatomic, strong) NSMutableArray *friendKeyArray; // 好友姓名首字母key
@property (nonatomic, strong) NSMutableDictionary *headerIsSelect; // 判断分区头是否被点
@property (nonatomic, strong) NSMutableArray *isSelectedPeopleArray; // 存储被选中的人

@property (nonatomic, assign) BOOL isSearch; // 判断是否搜索
@property (nonatomic, strong) NSMutableArray *peopleArrayWhenSearch; // 搜索时的全部数据
@property (nonatomic, strong) NSMutableArray *peopleArrayWhenSearchInIt; // 此时组的数值一直不会变化，之后初始化一次
@property (nonatomic, strong) NSMutableArray *peopleDataWhenSearch; // 搜索是的临时数据源

@property (nonatomic, strong) UIView *whiteBackView;
@property (nonatomic, strong) UIImageView *searchView;
@property (nonatomic, strong) UITextField *searchTF;


@end

@implementation CreateGroupFinishViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];
    // 建立数据源
    [self addData];
    // 布局视图
    [self addMySubview];
    
}

// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"创建小组";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(finish:)];
    rightItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 下一步
- (void)finish:(UIBarButtonItem *)rightItem
{
    NSLog(@"被选中的人: %@", self.isSelectedPeopleArray);
    
}

#pragma mark - 建立数据源
- (void)addData
{
 // 临时数据
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Class25ContactList" ofType:@"plist"];
    NSDictionary *tempDic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray *nameArray = [tempDic allKeys];
    self.friendNameDic = [NSMutableDictionary dictionary];
    for (int i = 0; i < nameArray.count; i++) {
        NSString *key = nameArray[i];
        NSArray *tempArray = [tempDic valueForKey:key];
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *myDic in tempArray) {
            SelectFriendModel *friendModel = [[SelectFriendModel alloc] init];
            [friendModel setValuesForKeysWithDictionary:myDic];
            [array addObject:friendModel];
        }
        [self.friendNameDic setValue:array forKey:nameArray[i]];
    }
    NSLog(@"dic = %@", self.friendNameDic);
    NSArray *oneArray = [[self.friendNameDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    self.friendKeyArray = [NSMutableArray arrayWithArray:oneArray];
    // 初始化分区头字典
    self.headerIsSelect = [NSMutableDictionary dictionary];
    for (int i = 0; i < nameArray.count; i++) {
        NSString *key = nameArray[i];
        [self.headerIsSelect setValue:@"NO" forKey:key];
    }
    NSLog(@"self.headerIsSelect = %@", self.headerIsSelect);
    
    // 初始化存储字典
    self.isSelectedPeopleArray = [NSMutableArray array];
    // 初始化搜索的全部数组, 里面存放的是所有model
    self.peopleArrayWhenSearchInIt = [NSMutableArray array];
    for (int i = 0; i < nameArray.count; i++) {
        NSString *key = nameArray[i];
        NSArray *tempArray = [tempDic valueForKey:key];
        for (NSDictionary *myDic in tempArray) {
            SelectFriendModel *friendModel = [[SelectFriendModel alloc] init];
            [friendModel setValuesForKeysWithDictionary:myDic];
            [self.peopleArrayWhenSearchInIt addObject:friendModel];
        }
    }
    
    // 初始化搜索时的临时数据
    self.peopleDataWhenSearch = [NSMutableArray array];
}

#pragma mark - 布局视图
- (void)addMySubview
{
    self.linkPeopleTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 44 * kAdjustParamater) style:UITableViewStyleGrouped];
    self.linkPeopleTableView.dataSource = self;
    self.linkPeopleTableView.delegate = self;
    self.linkPeopleTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_linkPeopleTableView];
    
    
   
    
    [self subviewHeader];
    
}

#pragma mark - 重新布局表头
- (void)subviewHeader
{
    self.whiteBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 65 * kAdjustParamater)];
    self.whiteBackView.userInteractionEnabled = YES;
    self.whiteBackView.backgroundColor = [UIColor whiteColor];
    
    self.searchView = [[UIImageView alloc] init];
    
    self.searchView.image = [UIImage imageNamed:@"tianjiahaoyoutubiao-tianjia"];
    [self.whiteBackView addSubview:_searchView];
    self.searchTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    self.searchTF .userInteractionEnabled = YES;
    self.searchTF.textAlignment = NSTextAlignmentLeft;
    self.searchTF .text = @"搜索";
    self.searchTF .clearsOnBeginEditing = YES;
    self.searchTF .textColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
   // self.searchTF.placeholder = @"搜索";
    self.searchTF .textAlignment = NSTextAlignmentLeft;
    self.searchTF .font = [UIFont systemFontOfSize:k16Big];
    self.searchTF.tintColor = kCyanColor;
    self.searchTF .delegate = self;
    [self.searchTF  addTarget:self action:@selector(TFChange:) forControlEvents:UIControlEventAllEditingEvents];
    [self.whiteBackView addSubview:_searchTF];
    UILabel *blackLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 63 * kAdjustParamater, kScreenWidth, 2 * kAdjustParamater)];
    blackLine.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
    [self.whiteBackView addSubview:blackLine];
    if (self.isSelectedPeopleArray.count > 0) {
        // 动态布局
        for (int i = 0; i < self.isSelectedPeopleArray.count; i++) {
            SelectFriendModel *model = self.isSelectedPeopleArray[i];
            UIImageView *tempImageV = [[UIImageView alloc] initWithFrame:CGRectMake(10 * kAdjustParamater + 60 * kAdjustParamater * i, 7 * kAdjustParamater, 50 * kAdjustParamater, 50 * kAdjustParamater)];
            tempImageV.userInteractionEnabled = YES;
            tempImageV.layer.cornerRadius = tempImageV.width / 2;
            tempImageV.layer.masksToBounds = YES;
            tempImageV.tag = 100 + i;
            tempImageV.image = [UIImage imageNamed:model.picture];
            [self.whiteBackView addSubview:tempImageV];
            // 添加手势
            UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelPeople:)];
            [tempImageV addGestureRecognizer:tapGes];
        }
        // 取得最后一个图片
       // UIImageView *tempImage = (UIImageView *)[self.view viewWithTag:99 + self.isSelectedPeopleArray.count];
     //   NSLog(@"tempImage.left = %f", tempImage.left);
        CGFloat right = 10 * kAdjustParamater + 60 * kAdjustParamater * self.isSelectedPeopleArray.count;
       
        self.searchView.frame = CGRectMake(right, 22 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater);
      self.searchTF.frame = CGRectMake(self.searchView.right + 10 * kAdjustParamater, 22 * kAdjustParamater, 50 * kAdjustParamater, 20 * kAdjustParamater);
       
        

    } else {

        self.searchView.frame = CGRectMake(25 * kAdjustParamater, 22 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater);
        self.searchTF.frame = CGRectMake(self.searchView.right + 10 * kAdjustParamater, 22 * kAdjustParamater, 50 * kAdjustParamater, 20 * kAdjustParamater);
    }
     self.linkPeopleTableView.tableHeaderView = self.whiteBackView;
}

#pragma mark - 取消好友
- (void)cancelPeople:(UITapGestureRecognizer *)tapGes
{
    NSInteger section = tapGes.view.tag - 100;
    SelectFriendModel *model = self.isSelectedPeopleArray[section];
    [self.isSelectedPeopleArray removeObjectAtIndex:section];
    [self subviewHeader];
    // 找到对应的model
    for (int i = 0; i < self.friendKeyArray.count; i++) {
        NSString *key = self.friendKeyArray[i];
        for (SelectFriendModel *tempModel in self.friendNameDic[key]) {
            if (model == tempModel) {
                tempModel.isSelect = NO;
            }
        }
    }
    [self.linkPeopleTableView reloadData];
}

#pragma mark - 搜索

- (void)TFChange:(UITextField *)textField
{
    NSLog(@"textField = %@", textField.text);
    // 每次textField变化就初始化一次
    self.peopleArrayWhenSearch = [NSMutableArray array];
    if (textField.text.length == 0) {
      //  textField.text = @"搜索";
        // 说明不需要搜索
        self.isSearch = NO;
    } else {
        self.isSearch = YES;
        for (SelectFriendModel *tempModel in self.peopleArrayWhenSearchInIt) {
            if ([tempModel.name containsString:textField.text]) {
                
//                if (self.peopleDataWhenSearch.count == 0) {
//                    // 需要添加一个model
//                     [self.peopleDataWhenSearch addObject:tempModel];
//                } else {
//                    for (int i = 0; i < self.peopleDataWhenSearch.count; i++) {
//                        SelectFriendModel *selectModel = self.peopleDataWhenSearch[i];
//                        if (selectModel == tempModel) {
//                            
//                        } else {
//                            [self.peopleDataWhenSearch addObject:tempModel];
//                        }
//                    }
//                    
            //    }
                [self.peopleArrayWhenSearch addObject:tempModel];
            }
        }
    }
    NSLog(@"self.peopleArrayWhenSearch = %@", self.peopleArrayWhenSearch);
    [self.linkPeopleTableView reloadData];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.isSearch == NO) {
        return self.friendKeyArray.count;
    }
    // 说明是搜索
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isSearch == NO) {
        NSString *key = self.friendKeyArray[section];
        NSString *isSelected = [self.headerIsSelect valueForKey:key];
        if ([isSelected isEqualToString:@"YES"]) {
            // 说明需要打开
            NSArray *value = self.friendNameDic[key];
            return value.count;
        } else {
            // 说明需要关闭
            return 0;
        }
    }
    // 说明是搜索
    return self.peopleArrayWhenSearch.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *identifier = @"AddMember";
    AddGroupMemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[AddGroupMemberTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.isSearch == NO) {
        NSString *key = self.friendKeyArray[indexPath.section];
        NSArray *value = self.friendNameDic[key];
        SelectFriendModel *model = value[indexPath.row];
        cell.model = model;
    } else {
        SelectFriendModel *model = self.peopleArrayWhenSearch[indexPath.row];
        cell.model = model;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65 * kAdjustParamater;
}

// 点击回调
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isSearch == NO) {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        NSString *key = self.friendKeyArray[indexPath.section];
        NSArray *value = self.friendNameDic[key];
        SelectFriendModel *model = value[indexPath.row];
        NSLog(@"选中了没有：%d", model.isSelect?YES:NO);
        //model.isSelect = !model.isSelect;
        if (model.isSelect == NO) {
            model.isSelect = YES;
        } else if (model.isSelect == YES) {
            model.isSelect = NO;
        }
        
        // 存储选中的人
        if (model.isSelect == YES) {
            
            [self.isSelectedPeopleArray addObject:model];
        } else {
            [self.isSelectedPeopleArray removeObject:model];
        }
        NSLog(@"被选中的数组:%@", self.isSelectedPeopleArray);
        // 重新布局表头
        [self subviewHeader];
    } else if (self.isSearch == YES) {
        
        // 取消第一响应者
        [self.searchTF resignFirstResponder];
        self.isSearch = NO;
        
        // 说明是搜索，点击选中cell并且将cell加入到isSelectedPeopleArray数组中
        SelectFriendModel *model = self.peopleArrayWhenSearch[indexPath.row];

        // 遍历当前的isSelectedPeopleArray数组判断是否有点击的model
        if (self.isSelectedPeopleArray.count == 0) {
            // 如果数组为空需要先添加一个model
            
            for (NSString *key in self.friendKeyArray) {
                NSArray *valueArray = self.friendNameDic[key];
                for (SelectFriendModel *modelOne in valueArray) {
                    if (modelOne.name == model.name) {
                        modelOne.isSelect = YES;
                        [self.isSelectedPeopleArray addObject:modelOne];
                    }
                }
            }
        } else if (self.isSelectedPeopleArray.count > 0) {
            NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.isSelectedPeopleArray];
            // 默认为可以添加
            NSInteger result = 1;
            for (int i = 0; i < tempArray.count; i++) {
                
                SelectFriendModel *tempModel = self.isSelectedPeopleArray[i];
                NSLog(@"tempModel.name = %@, model.name = %@", tempModel.name, model.name);
                NSInteger j = 0;
                if ([tempModel.name isEqualToString:model.name]) {
                    // 说明已经有了不能添加
                    NSLog(@"已经有了");
                    j = 0;
                } else {
                    j = 1;
                }
                result = result * j;
            }
            if (result == 1) {
                // 说明可以添加
                for (NSString *key in self.friendKeyArray) {
                    NSArray *valueArray = self.friendNameDic[key];
                    for (SelectFriendModel *modelOne in valueArray) {
                        if (modelOne.name == model.name) {
                            modelOne.isSelect = YES;
                            [self.isSelectedPeopleArray addObject:modelOne];
                        }
                    }
                }
            }
            
                
            
 
        }
        
        NSLog(@"被选中的数组:%@", self.isSelectedPeopleArray);
       
        
        
        // 重新布局表头
       [self subviewHeader];
    }
    
    [self.linkPeopleTableView reloadData];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.isSearch == YES) {
        // 说明是搜索状态
        return nil;
    }
    // 获取key
    NSString *key = self.friendKeyArray[section];
    UIView *grayVIew = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 25 * kAdjustParamater)];
    grayVIew.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.03];
    grayVIew.tag = section + 200;
    UIImageView *selectImage = [[UIImageView alloc] initWithFrame:CGRectMake(20 * kAdjustParamater, 2 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater)];
    // 获取是否选择
    NSString *isSelected = [self.headerIsSelect valueForKey:key];
    if ([isSelected isEqualToString:@"NO"]) {
        selectImage.image = [UIImage imageNamed:@"huisejiantou-createGroup"];
    } else {
         selectImage.image = [UIImage imageNamed:@"cyanjiantou-createGroup"];
    }
    [grayVIew addSubview:selectImage];
    UILabel *result = [[UILabel alloc] initWithFrame:CGRectMake(selectImage.right + 10 * kAdjustParamater, 2 * kAdjustParamater, 100 * kAdjustParamater, 20 * kAdjustParamater)];
    // result.backgroundColor = [UIColor redColor];
    
    result.text = key;
    result.textColor = kCyanColor;
    result.textAlignment = NSTextAlignmentLeft;
    result.font = [UIFont systemFontOfSize:k13Big];
    [grayVIew addSubview:result];
    
    // 添加手势
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeMember:)];
    [grayVIew addGestureRecognizer:tapGes];
 
    return grayVIew;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.isSearch == YES) {
        return 0;
    }
    return 25 * kAdjustParamater;
}

- (void)changeMember:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"手势执行");
    NSInteger section = tapGes.view.tag - 200;
     NSString *key = self.friendKeyArray[section];
    // 改变headerIsSelect
    NSString *isSelected = [self.headerIsSelect valueForKey:key];
    if ([isSelected isEqualToString:@"NO"]) {
        [self.headerIsSelect setValue:@"YES" forKey:key];
    } else {
        [self.headerIsSelect setValue:@"NO" forKey:key];
    }
    [self.linkPeopleTableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 3 * kAdjustParamater;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 3 * kAdjustParamater)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
